package com.camundademo.rest.dto;

import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 业务返回结果
 */
@Setter
@Getter
public class Results<T> {

    /**
     * 业务操作代码 (正常,异常)
     */
    private String code;

    /**
     * 业务消息
     */
    private String msg;

    /**
     * 业务数据
     */
    private T data;


    @AllArgsConstructor
    @Getter
    public enum RespEnum {
        SUCCESS("0", "成功"),
        ERROR("500", "失败");

        private String code;
        private String describe;

    }

    public static <T> Results<T> res(
            String code,
            String msg,
            T data
                                    ) {
        Results<T> results = new Results<T>();
        results.setCode(code);
        results.setMsg(msg);
        results.setData(data);
        return results;
    }

    //处理成功
    public static <T> Results<T> ok(T data) {
        Results<T> results = new Results<T>();
        results.setCode(RespEnum.SUCCESS.getCode());
        results.setMsg(RespEnum.SUCCESS.getDescribe());
        results.setData(data);
        return results;
    }

    /**
     * 通过HttpServletResponse响应流返回
     *
     * @param response
     * @param inputStream
     */
    public static void responseDoOutputStream(
            HttpServletResponse response,
            final InputStream inputStream
                                             ) {
        try (
                //资源文件流 输入
                InputStream resourceAsStream = inputStream;
                //响应输出流
                OutputStream out = response.getOutputStream()) {
            //下载文件
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = resourceAsStream.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
